﻿$(function () {

    //元素active效果生效
    document.body.addEventListener('touchstart', function () {});

    /** 短信发送倒计时 **/
    $('.send-btn').on('click', function () {
        countdown($(this));
    });
    /** 登录 **/
    $('.login-send').on('click', function () {
        var mobile = $('.validate-mobile').val();
        var re = /^0?1[3|4|5|7|8][0-9]\d{8}$/;
        //首先判断是否填写了手机号
        if(mobile){
            //正则匹配手机号
            if(re.test(mobile)){
                var param = {
                    mobile: mobile,
                    type: 'login'
                };
                PKTZ_API.getVerifyCode(param, countdown);
            }else $.mvalidateTip('请输入正确的手机号！')
        }else $.mvalidateTip('请输入手机号！')
    });


    /** 个人中心 **/
    //参赛身份更换
    $('#identity').on('click', function () {
        var userType = $(this).find('.personType').data('userType');
        var $options = $(this).data('options');

        if(userType == 1 || $options.length == 0){
            return
        }else {
            var options = JSON.parse($options);
            weui.picker(options, {
                onChange: function (result) {
                    //console.log(result);
                },
                onConfirm: function (result) {
                    var label = result[0].label;
                    var value = result[0].value;
                    $('#identity .right-side').text(label);
                    $('.personal-information').find('.personType').text(label);
                    var param = {
                        mobile: PKTZ_API.getCookie('memberMobile'),
                        userType: value
                    };
                    PKTZ_API.updateUserType(param);
                }
            });
        }

    });

    //参赛口号修改
    $('#slogan').on('click', function () {
        weui.dialog({
            title:"队伍口号",
            content:"<input type='text' placeholder='请输入队伍口号' class='kouHao'>",
            buttons: [
                {
                    label: "取消",
                    type: "default",
                    onClick: function () {}
                },
                {
                    label: "确定",
                    type: "primary",
                    onClick: function () {
                        var slogan = $('.kouHao').val();
                        $('#slogan .slogan').text(slogan);
                        var param = {
                            teamId: $('.team-information').find('.teamName').data('teamId'),
                            slogan: slogan
                        }
                        PKTZ_API.updateTeamInformation(param);
                    }
                }
            ]
        });
    });
    
    //邀请（生成二维码）`
    $('.invite-btn').on('click', function () {
        var that = this;
        $('.qr-box').fadeIn(500, function () {
            var param = {
                teamId: $(that).parents('.team-content').find('.teamName').data('teamId')
            };
            PKTZ_API.createQRcode(param);
        });
    });
    $('.qr-box .close').on('click', function () {
        $('.qr-box').fadeOut(500, function () {
            $('#qrCode').empty();
        });
    });

    //退出登录
    $('#logout').on('click', function () {
        weui.dialog({
            title:" ",
            content:"是否退出登录？",
            buttons: [
                {
                    label: "取消",
                    type: "default",
                    onClick: function () {}
                },
                {
                    label: "确定",
                    type: "primary",
                    onClick: function () {
                        PKTZ_API.userLogout();
                    }
                }
            ]
        });
    });
    //队伍切换
    $('.team-information .team-tab_content').find('.item').on('click', function () {
       $(this).addClass('active').siblings().removeClass('active');
       var id = $(this).index();
       $('.team-information').find('.team-content').eq(id).addClass('active').siblings().removeClass('active');
    });

    /** 风采展示、报名 **/

    //风采展示点击擂主查看风采详情
    $('#showList li .left-bar').on('click', function () {
        var matchArea = $(this).parent('li').attr('title-id');
        document.cookie =  'matchArea=' + encodeURI(matchArea);
        PKTZ_API.getPageRoute('style_detail');
        //window.location.href = 'style_detail.html'
    });

    $('#zone-list ul li').on('click', function () {
        var matchArea = $(this).find('.title').text();
        document.cookie =  'matchArea=' + encodeURI(matchArea);
        PKTZ_API.getPageRoute('style_detail');
        //window.location.href = 'style_detail.html'
    })

    //挑战他
    $('#challengeBtn').on('click', function () {
        var status = $(this).data('status');
        var isFull = $(this).data('isFull');
        if(isFull){
            $.mvalidateTip('本赛区挑战队伍已满，请选择其它赛区！');
        }else {
            switch (status) {
                case 0:
                    $.mvalidateTip('请先登录！');
                    break;
                case 1:
                    $('#challengeDialog').show();
                    break;
                case 2:
                    $.mvalidateTip('已经报名挑战，不能继续挑战！');
                    break;
                case 3:
                    $.mvalidateTip('不同赛区不能进行挑战！');
                    break;
                case 4:
                    $.mvalidateTip('只有领队才能发起挑战！');
                    break;
            }
        }

    });

    //赛区选择
    $('#zone').on('click', function () {
        var str = $(this).data('options');
        if(!str) {
            $(this).blur();
            return
        }
        var options = JSON.parse(str);
        if(options.length == 0){
            $.mvalidateTip('无可挑战医院!');
        }else {
            weui.picker(options, {
                onChange: function (result) {},
                onConfirm: function (result) {
                    var label = result[0].label;
                    var value = result[0].value;
                    var name = result[0].name;
                    $('#zone').val(label).data('groupId', value);
                    $('#zone').data('matchArea', name);
                }
            });
        }
    });

    //报名
    $('#sure').on('click', function () {
        var teamId =  $('#challengeDialog').find('.hospital').data('teamId');
        var matchArea = $('#zone').data('matchArea');
        if(teamId && matchArea){
            var param = {
                teamId: teamId,
                matchArea: matchArea
            };
            PKTZ_API.submitBaoming(param);
            //$('#hospital-name, #zone').val('');
            return
        }
        $.mvalidateTip('请选择医院及赛区！')

    });

    //新增医院信息填写
    $('.add_hospital').on('click', function () {
        $('.block-choice').fadeIn();
    });

    //新增医院
    $('.add-sure').on('click', function () {
        var area = $('#area').val();
        $('.block-choice').find('input[type="text"]').each(function () {
           var msg = $(this).attr('placeholder');
           var val = $(this).val();
           if(!val){$.mvalidateTip(msg);}
        });
        var hospital = $('.block-choice').find('.add-hospital-name').val();
        var level = $('.block-choice').find('#level').val();
        if(area && hospital && level){
            var param = {
                province: area.split(",")[0],
                city: area.split(",")[1],
                hospitalName: $('.add-hospital-name').val(),
                hospitalLevel: $('#level').val()
            };
            PKTZ_API.addHospital(param);
        }

    });
    //医院级别列表
    $('#level').on('click', function () {
        var options = JSON.parse($(this).data('options'));
        if(options.length > 0){
            weui.picker(options, {
                onChange: function (result) {
                    //console.log(result);
                },
                onConfirm: function (result) {
                    var label = result[0].label;
                    $('#level').val(label);
                    console.log(result);
                }
            });
        }
    });

    //关闭报名弹窗
    $('.dialog-body').on('click', function (e) {
        e.stopPropagation();
    });
    $('.block-choice').on('click', function (event) {
        var _con = $('.dialog-body');
        if(!_con.is(event.target) && _con.has(event.target).length === 0){
            $(this).fadeOut(500,function () {
                $('.block-choice .block1').css({left: '0', opacity: 1});
                $('.block-choice .block2').css({left: '100%', opacity: 0});
                $('#search-hospital').empty().hide();
            });          //淡出消失
        }
    });

    /** 注册 **/
    //搜索医院
    var serachtimer;
    $('#hospital-name').on('input', function () {
        var length = $('#hospital-name').val().length;
        if(length > 0){
            var keyword = {
                keyWords: $(this).val()
            };
            clearTimeout(serachtimer);
            serachtimer=setTimeout(function(){
                PKTZ_API.searchHospital(keyword)
            },500)


        }else {
            $('#search-hospital').hide();
        }

    });

    //选中医院
    $('#search-hospital').on('click', 'p', function () {
        var text = $(this).text();
        var hospitalId = $(this).attr('hospitalId');
        var groupId = $(this).attr('groupId');
        $('#hospital-name').val(text).data('hospitalId', hospitalId);
        $('#hospital-name').data('groupId', groupId);
        $('#search-hospital').empty().hide();

        var str = $('.teamName').val();
        if(str){
            $('.userType').val('');
            $('.teamName').val('');
            $('.teamName').data('teamID', '');
            var param = {
                position: $('.position').val(),
                groupId: $('#hospital-name').data('groupId'),
                teamId: $('.teamName').data('teamID') || ''
            };
            PKTZ_API.getOptionalRoles(param);
        }
    });

    //发送手机短信
    $('.verify-btn').on('click', function () {
        var mobile = $('#mobile').val();
        var re = /^0?1[3|4|5|7|8][0-9]\d{8}$/;
        //首先判断是否填写了手机号
        if(mobile){
            //正则匹配手机号
            if(re.test(mobile)){
                var param = {
                    mobile: mobile,
                    type: 'register'
                };
                PKTZ_API.getVerifyCode(param,countdown);
            }else $.mvalidateTip('请输入正确的手机号！')
        }else $.mvalidateTip('请输入手机号！')
    });

    //选择职称
    $('.position').on('click', function () {
        var options = $(this).data('options');
        weui.picker(JSON.parse(options), {
            onChange: function (result) {
                //console.log(result);
            },
            onConfirm: function (result) {
                var label = result[0].label;
                $('#position').val(label);
                $('#teamName').removeAttr('disabled');

                $('.userType').val('');
                var param = {
                    position: $('.position').val(),
                    groupId: $('#hospital-name').data('groupId'),
                    teamId: $('.teamName').data('teamID') || ''
                };
                PKTZ_API.getOptionalRoles(param);

            }
        });
    });

    //选择队伍
    $('.teamName').on('click', function () {
        var hospitalId = $('#hospital-name').data('hospitalId');
        if(!hospitalId){
            $.mvalidateTip('请选择医院！');
            $(this).blur();
            return
        }
        $('.teamChoose').fadeIn();
        $('.teamChoose .body .item').remove();
        var param = {
            hospitalId: hospitalId
        };
        PKTZ_API.getTeamsByHospital(param);
    });
    //新增队伍
    $('.addTeam').on('click', function () {
        $('.teamChoose').fadeOut();
        weui.dialog({
            title:"队伍名称",
            content:"<input type='text' placeholder='请输入队伍名称' class='userAddTeam'>",
            buttons: [
                {
                    label: "取消",
                    type: "default",
                    onClick: function () {}
                },
                {
                    label: "确定",
                    type: "primary",
                    onClick: function () {
                        var teamName = $('.userAddTeam').val();
                        $('#teamName').val(teamName).data('teamID', '');
                        //获取参赛身份
                        var param = {
                            position: $('.position').val(),
                            groupId: $('#hospital-name').data('groupId'),
                            teamId: $('.teamName').data('teamID') || ''
                        };
                        PKTZ_API.getOptionalRoles(param);
                    }
                }
            ]
        });
    });

    //选择身份
    $('.userType').on('click', function () {
        var groupId = $('#hospital-name').data('groupId');
        var position = $('#position').val();
        var team = $('.teamName').val();
        if(!groupId){
            $.mvalidateTip('请选择医院！');
            return
        }
        if(!position){
            $.mvalidateTip('请选择身份！');
            return
        }
        if(!team){
            $.mvalidateTip('请选择队伍！');
            return
        }
        var options = JSON.parse($(this).data('options'));
        if(options.length == 0){
            $.mvalidateTip('当前职称在所选队伍无身份可选！')
        }else {
            weui.picker(options, {
                onChange: function (result) {
                    //console.log(result);
                },
                onConfirm: function (result) {
                    var label = result[0].label;
                    var value = result[0].value;
                    $('.userType').val(label);
                    $('.userType').data('userType', value);
                }
            });
        }
    });

    //选择BU
    $('.change-BU').on('click', function () {
        weui.picker([{
            label: 'CABU',
            value: 0
        },{
            label: 'CDBU',
            value: 1
        },{
            label: 'CXBU',
            value: 2
        },{
            label: 'DABU',
            value: 3
        }], {
            onChange: function (result) {
                //console.log(result);
            },
            onConfirm: function (result) {
                var label = result[0].label;
                $('.change-BU').val(label);
                result[0].disabled = true
                //console.log(result);
            }
        });
    });

    /** 答题 **/

    $('.single-ul').on('click','.options-ul li', function () {
        $(this).find('input[type="radio"]').prop('checked', true);
        var key = $(this).parent('.options-ul').data('key');
        var m = '';
        $(this).parent('.options-ul').find('li').each(function () {
            var a = $(this).find('input[type="radio"]:checked').val();
            if(a){
                m = a;
            }
        });
        $(this).parent('.options-ul').data('key', m);
        if(key && m == key) {
            return;
        }
        //ExamMethod.updateExam();
    });
    $('.multiple-ul').on('click','.options-ul li', function () {
        var check = $(this).find('input[type="checkbox"]').prop('checked');
        var key = $(this).parent('.options-ul').data('key');
        if(check){
            $(this).find('input[type="checkbox"]').prop('checked', false)
        }else $(this).find('input[type="checkbox"]').prop('checked', true);
        var m = '';
        $(this).parent('.options-ul').find('li').each(function () {
            var a = $(this).find('input[type="checkbox"]:checked').val();
            if(a){
                m += a;
            }
        });
        $(this).parent('.options-ul').data('key', m);
        if(key && m == key) {
            return;
        }
        //ExamMethod.updateExam();
    });
    $('#submitExam').on('click', function () {
        var notAnswer = 0;
        var title;
        $('.question-content').find('.options-ul').each(function () {
            var value = $(this).data('key');
            if(value == 0){
                notAnswer++
            }
        });
        if(notAnswer == 0){
            title = '已完成答题，是否提交？'
        }else {
            title = '还有'+ notAnswer +'道题目未答，是否提交？'
        }
        weui.dialog({
            content: title,
            className: 'custom-classname',
            buttons: [{
                label: '取消',
                type: 'default',
                onClick: function () {

                }
            }, {
                label: '确定',
                type: 'primary',
                onClick: function () {
                    ExamMethod.submitExams(function () {
                        $('.answer-end').show();
                    });
                }
            }]
        });

    });
    //再次挑战
    $('.answer-end .btn-group').find('.again').on('click', function () {
        PKTZ_API.getPageRoute('challenger');
    })
    //查看答题记录
    $('.answer-end .btn-group').find('.record').on('click', function () {
        PKTZ_API.getPageRoute('exam_record');
    })

});
var ExamMethod = {
    submitExams: function (callback) {
        var list = [];
        $('.question-content').find('.options-ul').each(function () {
            var value = $(this).data('key');
            if(value){
                list.push(value);
            }else {
                value = 0;
                list.push(value);
            }
        });
        var answerTime = $('.question-content').data('answerTime');
        var remainingTime = $('.question-content').data('remainingTime');
        var times = count > remainingTime ? remainingTime : count;
        var param = {
            id: $('.question-content').data('examId'),
            questionId: $('.question-content').data('questionId'),
            answerTime: times + answerTime,
            submitQuestionAnswer: list.join('|'),
            source: 2
        };
        PKTZ_API.submitExam(param,callback);
    },
    updateExam: function () {
        var list = [];
        $('.question-content').find('.options-ul').each(function () {
            var value = $(this).data('key');
            if(value){
                list.push(value);
            }else {
                value = 0;
                list.push(value);
            }
        });
        //已用答题时间
        var answerTime = $('.question-content').data('answerTime');
        //剩余答题时间
        var remainingTime = $('.question-content').data('remainingTime');
        var times = count > remainingTime ? remainingTime : count;
        var param = {
            id: $('.question-content').data('examId'),
            answerTime: times + answerTime,
            submitQuestionAnswer: list.join('|')
        };
        PKTZ_API.updateExam(param);
    },
    updateAuto: function () {
        var s;
        var number = 0;
        s = setInterval(function () {
            number++;
            var remainingTime = $('.question-content').data('remainingTime');
            if(number%5 == 0 && remainingTime){
                ExamMethod.updateExam();
            }
            if(number == remainingTime) clearInterval(s);
        }, 1000);
    }
};

function countdown(element) {
    var s;
    var timer = 60;
    s = setInterval( function () {
        if(timer > 0){
            timer--;
            element.text('（ '+ timer +' ）').attr('disabled', true).css('background', '#dddddd');
        }else {
            clearInterval(s);
            element.text('重新发送').attr('disabled', false).css('background', '#F4ACBE');
            timer = 60;
            return
        }
    }, 1000)
}


